
# -*- coding: gb2312 -*-

from pymongo import MongoClient

from WindPy import *

from datetime import date

import time

def extractDailyClose():
    startMonthDateStr = '2012-01'

    startDateStr = startMonthDateStr + '-01'

    currDateStr = time.strftime('%Y-%m-%d')

    w.start()


    resStockID = w.wset('sectorconstituent','date=' + currDateStr + ';sectorid=a001010100000000;field=wind_code')

    stockIDdata = resStockID.Data[0]


    totalStockIDnum = len(stockIDdata)

    stockIdList = []

    for i in range(0, totalStockIDnum):
        stockIdStr = str(stockIDdata[i])

        stockIdList.append(stockIdStr)

    stockIndexIDList = ['000001.SH', '399001.SZ', '399006.SZ', '000300.SH', '000016.SH', '000905.SH']

    stockIdList = stockIdList + stockIndexIDList

    totalStockIDnum = len(stockIdList)



    client = MongoClient('localhost', 27017)

    db_name = 'stocks'

    db = client[db_name]

    collection_dailyclose = db['daily_close_prefill2']


    #aData = [{'TDate': '2015-01-01', 'StockID': '000001.SZ', 'Close': 23.433}, {'TDate': '2015-01-01', 'StockID': '000002.SZ', 'Close': 13.43}]



    #collection_dailyclose.insert(aData)

    for stockNdx in range(0, totalStockIDnum):
        oneStockID = stockIdList[stockNdx]
        resDailyClose = w.wsd(oneStockID, 'close', startMonthDateStr, currDateStr, 'Fill=Previous;PriceAdj=F')
        closeDataNum = resDailyClose.Data[0]
        closeDataTime = resDailyClose.Times
        totalTransDaysNum = len(closeDataNum)
        aData = []
        aDateDict = {}
        aDateDict['StockID'] = oneStockID
        for tDayNum in range(0, totalTransDaysNum):

            aDateDict[closeDataTime[tDayNum].strftime('%Y-%m-%d')] =closeDataNum[tDayNum]

            #aDateDict['Close'] = closeDataNum[tDayNum]
        aData.append(aDateDict)
        collection_dailyclose.insert(aData)

        print('Stock: ' + oneStockID + ' finished writing to MongoDB...')

#db.daily_close_prefill.find({}, {'StockID':1, '2012-01-04':1})





